from flask import render_template,flash, redirect, request, url_for
from flask_login import login_user, logout_user, login_required, current_user
from . import auth
from .forms import LoginForm, RegistrationForm
from ..models import User
from ..email import send_email
from app import db

@auth.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit(): 
        user = User.query.filter_by(email=form.email.data).first() 
        if user is not None and user.verify_password(form.password.data): 
            login_user(user, form.remember_me.data) 
            next = request.args.get('next') 
            if next is None or not next.startswith('/'): 
                next = url_for('main.index') 
            return redirect(next) 
        flash('用户名或密码错误') 
    return render_template('auth/login.html', form=form)

@auth.route('/logout')
@login_required
def logout():
    logout_user()
    flash('你已经退出了') 
    return redirect(url_for('main.index'))


# 注册路由
@auth.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(email=form.email.data,
                    username=form.username.data,
                    password=form.password.data)
        db.session.add(user)
        db.session.commit()
        # 生成令牌，发送邮件
        token = user.generate_confirmation_token() 
        send_email(user.email, 'Confirm Your Account', 
                   'auth/email/confirm', user=user, token=token) 
        flash('一封确认邮件已经发送到你的邮箱！', 'success') 
        return redirect(url_for('auth.login'))
    return render_template('auth/register.html', form=form)

# 确认账户路由
@auth.route('/confirm/<token>') 
@login_required 
def confirm(token): 
    # 若已经确认，跳转到首页
    if current_user.confirmed: 
        return redirect(url_for('main.index')) 
    
    # 验证令牌，若正确则提交到数据库
    if current_user.confirm(token): 
        db.session.commit() 
        flash('你已经确认的邮件. 感谢注册!', 'danger') 
    else: 
        flash('The confirmation link is invalid or has expired.') 
    return redirect(url_for('main.index'))

# 请求前验证当前用户
@auth.before_app_request 
def before_request(): 
    if current_user.is_authenticated: 
        current_user.ping() 
        if not current_user.confirmed \
            and request.endpoint \
            and request.blueprint != 'auth' \
            and request.endpoint != 'static': 
            return redirect(url_for('auth.unconfirmed')) 

# 未确认用户的路由
@auth.route('/unconfirmed') 
def unconfirmed(): 
    if current_user.is_anonymous or current_user.confirmed: 
        return redirect(url_for('main.index')) 
    return render_template('auth/unconfirmed.html')

# 确认用户的路由
@auth.route('/confirm') 
@login_required 
def resend_confirmation(): 
    token = current_user.generate_confirmation_token() 
    send_email(current_user.email, '确认你的账户', 
               'auth/email/confirm', user=current_user, token=token) 
    flash('新的确认邮件已经发送到你的邮箱！', 'warning') 
    return redirect(url_for('main.index'))